import imaplib
import email
host = 'imap.163.com'

username = '18620358128@163.com'
password = 'development73'


def get_inbox():
    imaplib.Commands['ID'] = ('AUTH')
    args = ("name", "IMAPClient", "version", "0.1.0", "vendor", "walker")
    mail = imaplib.IMAP4_SSL(host)
    mail.login(username, password)
    typ, dat = mail._simple_command('ID', '("'+'" "'.join(args)+'")')
    print(mail._untagged_response(typ, dat, 'ID'))

    mail.select("INBOX")

    _, search_data = mail.search(None, '(TO 11860083@qq.com)')

    my_message = []
    for num in search_data[0].split():
        email_data = {}
        _, data = mail.fetch(num, '(RFC822)')
        _, b = data[0]
        email_message = email.message_from_bytes(b)
        for header in ['subject', 'to', 'from', 'date']:
            email_data[header] = email_message[header]
        for part in email_message.walk():
            if part.get_content_type() == u'text/plain':
                body = part.get_payload(decode=True)
                email_data['body'] = body.decode()
            elif part.get_content_type() == 'text/html':
                html_body = part.get_payload(decode=True)
                email_data['html_body'] = html_body.decode()
        my_message.append(email_data)
    mail.logout()
    return my_message


if __name__ == '__main__':
    my_inbox = get_inbox()
    print(my_inbox)
